package v1

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"jwgin/model"
	"jwgin/model/mysql"
	"jwgin/service"
	"jwgin/utils/jw"
	"jwgin/utils/salt"
	signs "jwgin/utils/sign"
	"jwgin/utils/sms"
	"unicode/utf8"
)

type login struct{}

func (l *login) Routers(Router *gin.RouterGroup) (R gin.IRoutes) {
	Router.POST("login", l.post)
	Router.PUT("login", l.put)
	Router.PUT("sms", l.sms)
	return Router
}

//登录
func (login) post(c *gin.Context) {
	q := &model.UserLogin{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, fmt.Errorf("参数错误"))
		return
	}

	users := &mysql.User{}
	if err := service.G.Where("account = ? ", q.Account).First(users).Error; err != nil {
		RespErr(c, fmt.Errorf("没有这个账号"))
		return
	}

	// 密码校验
	if md5 := signs.HmacSha256(users.Salt, q.Password); md5 != users.Password {
		fmt.Println(q.Password, "=>", md5)
		RespErr(c, fmt.Errorf("密码错误"))
		return
	}

	if users.State == 1 {
		//返回token
		token := jw.SetToken(uint(users.Id), uint(users.Comid))
		ret := model.RespLogin{
			Username: users.Username,
			Account:  users.Account,
			Token:    token,
		}
		RespSucc(c, ret)
	} else {
		RespErr(c, fmt.Errorf("登录失败"))
	}

}

//获取验证码
func (login) sms(c *gin.Context) {
	q := &model.UserSms{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, fmt.Errorf("参数错误"))
		return
	}

	ip := c.ClientIP()
	sMs := sms.NewMb345()
	if err := sMs.SendSms(ip, q.Account); err != nil {
		RespErr(c, fmt.Errorf("验证码获取失败"))
		return
	} else {
		RespSucc(c, nil)
	}

}

//注册
func (login) put(c *gin.Context) {
	q := &model.UserRegister{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, fmt.Errorf("参数错误"))
		return
	}

	if len(q.Account) > 16 || len(q.Account) < 6 {
		RespErr(c, errors.New("账号6-16位"))
		return
	}

	if utf8.RuneCountInString(q.Nickname) > 16 || utf8.RuneCountInString(q.Nickname) < 6 {
		RespErr(c, errors.New("昵称6-16位"))
		return
	}

	if len(q.Password) > 16 || len(q.Password) < 6 {
		RespErr(c, errors.New("密码6-16位"))
		return
	}

	sMs := sms.NewMb345()
	if !sMs.CheckSms(q.Account, q.Code) {
		RespErr(c, errors.New("验证码错误"))
		return
	}

	//查一下当前用户账号存在没有
	h := &mysql.User{}
	if err := service.G.Model(&mysql.User{}).Where("account = ? ", q.Account).First(h).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			RespErr(c, errors.New("fail"))
			return
		}
	}
	if h.Id > 0 {
		RespErr(c, errors.New("该账号已被注册!!!"))
		return
	}

	u := &mysql.User{
		Username: q.Nickname,
		Account:  q.Account,
		State:    1,
	}
	u.Salt = salt.SaltStr(6)
	u.Password = signs.HmacSha256(u.Salt, q.Password)

	if err := service.G.Create(u).Error; err != nil {
		RespErr(c, errors.New("fail"))
	} else {
		RespSucc(c, nil)
	}
}
